const router = require('koa-router')()
const { getPassword } = require('../utils/crypto')
const { exec } = require('../db/index')
const jsonwebtoken = require('jsonwebtoken')

router.prefix('/api/users')

const auth = async(ctx, next) => {
  // 查看用户是否有token
  const { token = '' } = ctx.request.header;
  try {
    const user = jsonwebtoken.verify(token, 'wjWsksj_12')
    ctx.state.user = user;
  } catch(err) {
    ctx.throw(401, '没有权限')
  }
  await next()
}

const checkOwner = async(ctx, next) => {
  console.log(ctx.state.user.id, '----------------')
  if (ctx.state.user.id !== 1) {
     ctx.throw(402, '没有权限删除')
  }
  await next()
}

router.post('/login', async(ctx, next) => {
  // 参数校验
  const loginData = ctx.request.body;
  const sql = `select * from users where username='${loginData.username}' and password='${getPassword(loginData.password)}';`
  const data = await exec(sql);
  console.log(data, 'data--------------data')
  if (data.length) {
    const { id, username, password} = data[0]
      // token
    const token = jsonwebtoken.sign({id, username, password}, 'wjWsksj_12', { expiresIn: '48h' })
    ctx.body = { token }
  } else {
    ctx.body = {
      msg: 'no 数据'
    }
  }
})

// 要求，删除的过程中，检查用户登陆了没有, 检查用户有没有权限删除
router.get('/delete/:id', auth, async(ctx, next) => {
  const { id } = ctx.params; 
  const sql = `delete from  users where id=${id};`
  const data = await exec(sql);
  ctx.body = data
})

module.exports = router
